package com.eiei.utils;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import com.eiei.bean.MessageBean;
import com.eiei.common.CommonValue;

/**
 * 邮件工具类，发送和接受邮件
 * 
 * @author eiei
 * 
 */
public class EmailUtils {

	/**
	 * 根据配置文件来发送信息
	 * 
	 * @param messageBean
	 * @return
	 * @throws Exception
	 */
	public static boolean sendMessage(MessageBean messageBean) throws Exception {

		String host = "smtp.gmail.com";
		String username = CommonValue.PROPERTIES_MAP.get("current_account");
		String password = CommonValue.getPassword();
		Properties props = System.getProperties();
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.user", messageBean.getSender());
		props.put("mail.smtp.password", password);
		props.put("mail.smtp.port", "587");
		props.put("mail.smtp.auth", "true");

		String[] to = { messageBean.getReciver() };

		Session session = Session.getDefaultInstance(props, null);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(messageBean.getSender()));

		InternetAddress[] toAddress = new InternetAddress[to.length];

		// 获取地址的array
		for (int i = 0; i < to.length; i++) {
			toAddress[i] = new InternetAddress(to[i]);
		}

		for (int i = 0; i < toAddress.length; i++) {
			message.addRecipient(Message.RecipientType.TO, toAddress[i]);
		}
		message.setSubject(messageBean.getId());
		// 发送信息之前，已经对内容进行加密
		message.setText(messageBean.getContent());
		Transport transport = session.getTransport("smtp");
		transport.connect(host, username, password);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();

		// 发送成功后，设置发送信息
		messageBean.setCreateDate(new Date());

		return true;
	}

	/**
	 * 接受邮件
	 * 
	 * @return
	 * @throws Exception
	 */
	public static List<MessageBean> recive() throws Exception {
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		String username = CommonValue.PROPERTIES_MAP.get("current_account");
		String password = CommonValue.getPassword();
		
		List<MessageBean> result = new ArrayList<MessageBean>();
		
		// Get a Properties object
		Properties props = System.getProperties();
		props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
		props.setProperty("mail.pop3.socketFactory.fallback", "false");
		props.setProperty("mail.pop3.port", "995");
		props.setProperty("mail.pop3.socketFactory.port", "995");

		// 以下步骤跟一般的JavaMail操作相同
		
		Session session = Session.getDefaultInstance(props, null);
		session.setDebug(false);
		// 请将红色部分对应替换成你的邮箱帐号和密码
		URLName urln = new URLName("pop3", "pop.gmail.com", 995, null,
				username,password);
		Store store = session.getStore(urln);
		Folder inbox = null;
		try {
			store.connect();
			inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);
			FetchProfile profile = new FetchProfile();
			profile.add(FetchProfile.Item.ENVELOPE);
			Message[] messages = inbox.getMessages();
			inbox.fetch(messages, profile);
			// System.out.println("收件箱的邮件数：" + messages.length);
			for (int i = 0; i < messages.length; i++) {
				// 邮件发送者
				String from = decodeText(messages[i].getFrom()[0].toString());
				InternetAddress ia = new InternetAddress(from);
//				System.out.println("FROM:" + from);
//				// 邮件标题
//				System.out.println("TITLE:" + messages[i].getSubject());
//				// 邮件大小
//				System.out.println("content:" + messages[i].getContent());
//				// 邮件发送时间
//				System.out.println("DATE:" + messages[i].getSentDate());
				if (from.equals(CommonValue.PROPERTIES_MAP.get("to_account"))) {
					MessageBean temp = new MessageBean();
					temp.setId("F"+messages[i].getSubject());
					temp.setContent(messages[i].getContent().toString());
					temp.setCreateDate(messages[i].getSentDate());
					temp.setStatus(MessageBean.UNREADER);
					temp.setSender(CommonValue.PROPERTIES_MAP.get("to_account"));
					temp.setReciver(CommonValue.PROPERTIES_MAP.get("current_account"));
					result.add(temp);
				}

			}
		} finally {
			try {
				inbox.close(false);
			} catch (Exception e) {
			}
			try {
				store.close();
			} catch (Exception e) {
			}
		}
		return result;
	}

	protected static String decodeText(String text)
			throws UnsupportedEncodingException {
		if (text == null)
			return null;
		if (text.startsWith("=?GB") || text.startsWith("=?gb"))
			text = MimeUtility.decodeText(text);
		else
			text = new String(text.getBytes("ISO8859_1"));
		return text;
	}

}
